package mybatis;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisDemo {

    private static final Logger log = LoggerFactory.getLogger(MyBatisDemo.class);

    private static SqlSessionFactory sqlSessionFactory = null;

    static {
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {

        log.info("开始执行！！！！！！！！！！！！！！！！！！！");
        new Thread(()->selectById(1)).start();
        new Thread(()->selectById(1)).start();
        new Thread(()->selectById(1)).start();
    }

    private static void selectById(Integer id){
        try (SqlSession session = openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            User user = mapper.selectById(id);

        }
    }



    private static void selectNameById(Integer id){
        try (SqlSession session = openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            String name = mapper.selectNameById(id);
            //System.out.println(name);
        }
    }





    private static SqlSession openSession(){
        //事务自动提交
        return sqlSessionFactory.openSession(true);
    }
}
